package com.example.java_gobang.service;

import com.example.java_gobang.game.Room;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2022-08-16
 * Time: 12:19
 */
@Service
//管理房间
public class RoomService {
    private ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();
    private ConcurrentHashMap<Integer,String> userIdToRoomId = new ConcurrentHashMap<>();
    //添加 元素
    public void add(Room room, int userId1,int userId2){
        rooms.put(room.getRoomId(),room);
        userIdToRoomId.put(userId1,room.getRoomId());
        userIdToRoomId.put(userId2,room.getRoomId());
    }

    public void remove(String roomId, int userId1,int userId2){
        rooms.remove(roomId);
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }

    public Room getRoomById(String roomId){
        return rooms.get(roomId);
    }


    public Room getRoomBYUserId(int userId){
        String roomId = userIdToRoomId.get(userId);
        if(roomId == null){
            return null;
        }

        return rooms.get(roomId);
    }
}
